package com.kaibes.core.spring.utils;

import java.io.IOException;
import java.io.InputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;

@Component
public class YamlUtils {

    @Autowired
    private ObjectMapper objectMapper;
    private static YamlUtils instance;
    
    public static YamlUtils getInstance() {
        return instance;
    }
    
    public YamlUtils() {
        YamlUtils.instance = this;
    }
    
    public JsonNode readAsJsonFromResources(String path) throws IOException {
    	ClassPathResource source = new ClassPathResource(path);
    	Yaml yaml = new Yaml();
    	Object data = yaml.load(source.getInputStream());
        String json = objectMapper.writeValueAsString(data);
        JsonNode node = objectMapper.readTree(json);
        return node;
    }
    public JsonNode readAsJson(InputStream io) throws IOException {
    	Yaml yaml = new Yaml();
        Object data = yaml.load(io);
        String json = objectMapper.writeValueAsString(data);
        JsonNode node = objectMapper.readTree(json);
        return node;
    }
    public JsonNode readAsJson(String content) throws IOException {
        Yaml yaml = new Yaml();
        Object data = yaml.load(content);
        String json = objectMapper.writeValueAsString(data);
        JsonNode node = objectMapper.readTree(json);
        return node;
    }
    
    public String json2Yaml(JsonNode node) throws IOException {
        YAMLMapper mapper = new YAMLMapper();
        String yamlStr = mapper.writeValueAsString(node);
        return yamlStr;
    }
    
}
